package org.finesys.common.log.filter;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.log.trace.tracer.Tracer;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Objects;

import static org.finesys.common.log.constants.TraceConstants.*;

@Slf4j
public class LogHelperWebFluxFilter implements WebFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(prehandle(exchange));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    /**
     * 前置处理
     */
    private ServerWebExchange prehandle(ServerWebExchange exchange) {
        HttpHeaders httpHeaders = exchange.getRequest().getHeaders();
        try {
            String traceId = Objects.requireNonNull(httpHeaders.get(TRACE_ID)).get(0);
            String spanId = Objects.requireNonNull(httpHeaders.get(SPAN_ID)).get(0);
            String parentId = Objects.requireNonNull(httpHeaders.get(PARENT_ID)).get(0);
            Tracer.trace(traceId, spanId, parentId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(LogstashUtil.exceptionMarker(), "spring webflux tracer filter exception.", e);
        }
        return exchange;
    }
}
